package com.mashang.servlet.stu;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashang.servlet.clazz.ClazzAllListServlet;
import com.mashang.domain.Clazz;
import com.mashang.domain.Student;
import com.mashang.util.ResultView;
import com.mashang.util.StrUtil;
import com.mashang.vo.student.StudentView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet("/student1")
public class StudentServlet extends HttpServlet {

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String studentId = req.getParameter("studentId");
        ResultView view = new ResultView();
        if (studentId == null || studentId.equals("")) {
            view.setCode(300);
            view.setMsg("学生id为空!");
            //json工具  对象-》json格式的字符串    json格式的字符串转成对象
            ObjectMapper objectMapper = new ObjectMapper();
            //将对象转成json格式的字符串
            String jsonStr = objectMapper.writeValueAsString(view);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write(jsonStr);
            return;
        }
        List<Student> stuViewList = StudentListServlet.stuList;
        //循环遍历删除对应的学生信息   id：主键
        Iterator<Student> iterator = StudentListServlet.stuList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getStudentId().longValue() == Long.parseLong(studentId)) {
                iterator.remove();
            }
        }

        //json工具  对象-》json格式的字符串    json格式的字符串转成对象
        ObjectMapper objectMapper = new ObjectMapper();
        //将对象转成json格式的字符串
        String jsonStr = objectMapper.writeValueAsString(view);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(jsonStr);
        return;


    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String name = req.getParameter("name");
        String studentNo = req.getParameter("studentNo");
        if (name == null || "".equals(name)) {
            resp.getWriter().write("xxxx");
            return;
        }

        String age = req.getParameter("age");
        String classId = req.getParameter("classId");
        String phone = req.getParameter("phone");
        String remark = req.getParameter("remark");
        String sex = req.getParameter("sex");

        Student student = new Student();
        student.setStudentNo(studentNo);
        student.setName(name);
        if (StrUtil.isNotEmpty(age)) {
            student.setAge(Integer.valueOf(age));
        }
        if (StrUtil.isNotEmpty(classId)) {
            student.setClassId(Long.parseLong(classId));
        }
        student.setPhone(phone);
        student.setRemark(remark);
        student.setSex(sex);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        student.setCreateTime(simpleDateFormat.format(date));

        long l = System.currentTimeMillis();
        student.setStudentId(l);

        StudentListServlet.stuList.add(student);

        ResultView view = new ResultView();
        //json工具  对象-》json格式的字符串    json格式的字符串转成对象
        ObjectMapper objectMapper = new ObjectMapper();
        //将对象转成json格式的字符串
        String jsonStr = objectMapper.writeValueAsString(view);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(jsonStr);
        return;

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String studentId = req.getParameter("studentId");
        resp.setContentType("text/html;charset=utf-8");
        if (studentId == null || "".equals(studentId)) {
            resp.getWriter().write(new ObjectMapper().writeValueAsString(ResultView.fail(10000, "studentId为空")));
            return;
        }

        StudentView studentView = new StudentView();
        //根据studentId查询出对应的学生信息
        for (Student student : StudentListServlet.stuList) {
            if (student.getStudentId().longValue() == Long.parseLong(studentId)) {
                studentView.modelTranfView(student);

                //根据班级id查询出班级的名称，并将班级名称赋值给学生view对象
                if (student.getClassId() != null) {
                    for (Clazz clazz : ClazzAllListServlet.classViewList) {
                        if (student.getClassId().longValue() == clazz.getClassId().longValue()) {
                            studentView.setClassName(clazz.getName());
                            break;
                        }
                    }
                }

                break;
            }
        }

        resp.getWriter().write(new ObjectMapper().writeValueAsString(ResultView.successData(studentView)));

    }


    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //method为put这种方法，不能够使用req.getParameter这种方式获取
//        String name = req.getParameter("name");
//        System.out.println("name=" + name);

        BufferedReader reader = req.getReader();
        String paramEncodeStr = reader.readLine();
        System.out.println(paramEncodeStr);
        //解码
        String decodeParamStr = URLDecoder.decode(paramEncodeStr, "utf-8");
        System.out.println(decodeParamStr);

        Student uptStudent = new Student();
        //切割字符串
        String[] splitParamArr = decodeParamStr.split("&");
        for (String paramStr : splitParamArr) {
            String[] paramArr = paramStr.split("=");
            if ("age".equals(paramArr[0])) {
                if (paramArr.length == 1) {
                    uptStudent.setAge(null);
                }
                if (paramArr.length == 2) {
                    uptStudent.setAge(Integer.valueOf(paramArr[1]));
                }
            }
            if ("classId".equals(paramArr[0])) {
                uptStudent.setClassId(Long.valueOf(paramArr[1]));
            }
            if ("name".equals(paramArr[0])) {
                uptStudent.setName(paramArr[1]);
            }
            if ("studentId".equals(paramArr[0])) {
                uptStudent.setStudentId(Long.valueOf(paramArr[1]));
            }
            //剩下的字段自己补充
        }

        // 修改对象
        for (Student stu : StudentListServlet.stuList) {
            if (stu.getStudentId().longValue() == uptStudent.getStudentId().longValue()) {
                stu.setStudentId(uptStudent.getStudentId());
                stu.setName(uptStudent.getName());
                stu.setClassId(uptStudent.getClassId());
                stu.setAge(uptStudent.getAge());
                //修改引用，不起作用
//                stu = uptStudent;
                break;
            }
        }

        resp.getWriter().write(new ObjectMapper().writeValueAsString(ResultView.success()));


    }
}
